#!/usr/bin/env bash

#
# use QEMU's `hostfwd` to set network.
#

clean_env() {
    systemctl stop NetworkManager 2>/dev/null
    systemctl stop firewalld 2>/dev/null
    iptables -F 2>/dev/null
    nft flush ruleset 2>/dev/null
    # setenforce 0 2>/dev/null
}

ssh_login() {
    user="root"
    # passwd -d $user
    sed -ri."" 's/^ *#* *(PermitEmptyPasswords).*/\1 yes/' /etc/ssh/sshd_config
    sed -ri."" 's/^ *#* *(PermitRootLogin).*/\1 yes/' /etc/ssh/sshd_config
    sed -ri."" 's/^ *#* *(UsePAM).*/\1 yes/' /etc/ssh/sshd_config
    sed -ri."" 's/^ *#* *(UseDNS).*/\1 no/' /etc/ssh/sshd_config
    systemctl restart sshd \
        || service sshd restart \
        || systemctl restart ssh \
        || service ssh restart \
        || rc-service sshd restart \
        || rc-service ssh restart
}

set_pub_key() {
    PUBKEY="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDk/CSaXip7wwa2xsDaZm6eKmyET91fI28ufdVMZvsym7s8y0QVxdO16t9IlbH9ognp/zLETJSl1MxoEz1R2I9rE+R0eraeBT/LIsF5nIyMBZ/Zk5SRNrociW+9w4AxWZHcugGznVFIxbeC2Ja/q4xxDWRbtPB5nv2R92eTwZZ6TovxjmSGXUcBVRVFgvE0k7KgdRCGK9q0JOUZMT2d3fs8FkOJPeSznnawaUiLlLYFsY1R4F/+0r+zlbDgKrBmnjv1GYKohBcFMsw10m08cU3UjJym67R0I2NKMAFhWBZAh4IGMIfg7w3Ua2K4nHQwlcnOWuZ7jzll/nYRmrS9T3LF root@718f9c9841a8"
    sshpath="/root/.ssh"
    mkdir -p $sshpath
    echo $PUBKEY > ${sshpath}/authorized_keys
    chmod -R 0600 $sshpath
}

start_ttrexec_daemon() {
    cmd="ttrexec-daemon"
    cmd_path="/usr/local/bin/${cmd}"
    $cmd_path -a 0.0.0.0 -p 22000 2>/tmp/${cmd}_stderr.log >/tmp/${cmd}_stdout.log &
}

start_hawk_agent() {
    cmd="hawk-agent"
    (bash -x /usr/local/bin/${cmd}/tool/start.sh 2>/tmp/${cmd}_stderr.log >/tmp/${cmd}_stdout.log) &
}

clean_env
ssh_login
set_pub_key
start_ttrexec_daemon
start_hawk_agent
